package com.framework.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.framework.auth.service.AuthService;
import com.framework.auth.service.AuthService;
import com.framework.authorization.vo.UserDetailsVo;
import com.framework.common.Enums.UserTypeEnum;
import com.framework.common.request.CustomInfoReq;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author zhoubb
 * @version V1.0
 * @Date 2020/5/22 20:58
 * @since JDK 1.8
 */
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    @Override
    public void refreshTtzAuthentication(CustomInfoReq customInfoReq) {
        log.info("参数=[{}]", JSON.toJSONString(customInfoReq));
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        Optional<GrantedAuthority> role1 = ((UserDetailsVo)auth.getPrincipal()).getAuthorities().stream().findFirst();
        log.info("roleId before=[{}]", role1.get().getAuthority());
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(1);
        authorities.add(new SimpleGrantedAuthority(UserTypeEnum.getCode(Integer.valueOf(customInfoReq.getUserType()))));
        UserDetails userDetails = new UserDetailsVo(customInfoReq.getUserId().toString(), customInfoReq.getOpenId(), authorities);
        // 生成新的认证信息
        Authentication newAuth = new UsernamePasswordAuthenticationToken(userDetails, customInfoReq.getOpenId(), authorities);
        // 重置认证信息
        SecurityContextHolder.getContext().setAuthentication(newAuth);
        UserDetailsVo userDetails2 = (UserDetailsVo)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Optional<GrantedAuthority> role2 = userDetails2.getAuthorities().stream().findFirst();
        log.info("roleId after[{}]", role2.get().getAuthority());
    }
}
